<?php

namespace pam\Mapper;

/**
 * Description of UserDataAccess
 *
 * @author Robert Bwana
 */
use Zend\Db\Adapter\AdapterInterface;
use pam\Model\User;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Insert;
use Zend\Db\Sql\Update;
use Zend\Db\Sql\Delete;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Stdlib\Hydrator\HydratorInterface;

class UserDataAccess {

    protected $dbAdapter;
    protected $hydrator;
    protected $user;
    protected $table;

    public function __construct(AdapterInterface $dbAdapter, HydratorInterface $hydrator, User $user) {
        $this->dbAdapter = $dbAdapter;
        $this->hydrator = $hydrator;
        $this->user = $user;
        $this->table = 'pam_user';
    }

    public function delete($id) {

        $action = new Delete($this->table);
        $action->where(array(
            'id = ?' => $id
        ));

        $stmt = $sql->prepareStatementForSqlObject($action);
        $result = $stmt->execute();

        return (bool) $result->getAffectedRows();
    }

    /*
     * returns User
     */

    public function find($id) {
        $sql = new Sql($this->dbAdapter);
        $select = $sql->select($this->table);
        $select->where(array('id = ?' => $id));

        $stmt = $sql->prepareStatementForSqlObject($select);
        $result = $stmt->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult() && $result->getAffectedRows()) {
            return $this->hydrator->hydrate($result->current(), $this->user);
        } else {
            throw new \InvalidArgumentException("User with given ID:{$id} not found.");
        }
    }

    public function findAll() {
        $sql = new Sql($this->dbAdapter);
        $select = $sql->select($this->table);

        $stmt = $sql->prepareStatementForSqlObject($select);
        $result = $stmt->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new HydratingResultSet($this->hydrator, $this->policy);

            return $resultSet->initialize($result);
        } else {
            return array();
        }
    }

    public function save(User $user) {
        $userData = $this->hydrator->extract($user);
        unset($userData['id']);

        if ($user->getId()) {
            $action = new Update($this->table);
            $action->set($userData);
            $action->where(array('id = ?' => $user->getId()));
        } else {
            $action = new Insert($this->table);
            $action->values($userData);
        }

        $sql = new Sql($this->dbAdapter);
        $stmt = $sql->prepareStatementForSqlObject($action);
        $result = $stmt->execute();

        if ($result instanceof ResultInterface) {
            if ((bool) $newId = $result->getGeneratedValue()) {
                $user->setId($newId);
            }

            return $user;
        }
    }

}
